<template>
  <router-view></router-view>
  <login-view v-model:visible="isVisible.dialogLoginView" />
</template>

<script setup lang="ts">
import { useLocalStorage } from '@vueuse/core';
import { computed, onMounted, reactive, ref, watch } from 'vue';

import { localeConfigKey } from '@/locales/index';
import { useLocale } from '@/locales/useLocale';
import { useSettingStore, userSystemStore } from '@/store';
import { autoSync } from '@/utils/webdev';

import LoginView from '@/pages/login/LoginView.vue';

const storeSetting = useSettingStore();
const userInfo = userSystemStore();

const { changeLocale } = useLocale();

const isVisible = reactive({
  dialogLoginView: false,
});

const theme = computed(() => {
  return storeSetting.getStateMode;
});

const webdev = computed(() => {
  return storeSetting.webdev;
});

const intervalId = ref();

watch(
  () => webdev.value,
  (val) => {
    if (intervalId.value) clearInterval(intervalId.value);
    if (val.sync) {
      intervalId.value = setInterval(
        () => {
          autoSync(val.data.url, val.data.username, val.data.password);
        },
        1000 * 5 * 60,
      );
    }
  },
  { deep: true },
);
watch(
  () => storeSetting.displayMode,
  (val) => {
    const isDarkMode = val === 'dark';
    document.documentElement.setAttribute('theme-mode', isDarkMode ? 'dark' : '');
  },
);
watch(
  () => useLocalStorage(localeConfigKey, 'zh_CN').value,
  (val) => {
    changeLocale(val);
  },
);

onMounted(() => {
  initConfig();
});

const initConfig = async () => {
  console.log(userInfo.getUserInfo());
  isVisible.dialogLoginView = !userInfo.$state.loginFlag;
};

window.electron.ipcRenderer.on('system-theme-updated', (_, activeTheme) => {
  if (theme.value === 'auto') {
    const themeMode = activeTheme === 'dark' ? 'dark' : '';
    document.documentElement.setAttribute('theme-mode', themeMode);
    console.log(`system-theme-updated: ${activeTheme}`);
  }
});
</script>
